package com.ruoyi.door.controller.app.orderinfo;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.easy.query.api.proxy.entity.select.EntityQueryable;
import com.easy.query.core.api.pagination.EasyPageResult;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.door.controller.app.orderinfo.vo.AppOrderInfoCreateReqVO;
import com.ruoyi.door.controller.app.orderinfo.vo.AppOrderInfoSubmitReqVO;
import com.ruoyi.door.domain.DoorOrder;
import com.ruoyi.door.domain.DoorOrderDetail;
import com.ruoyi.door.domain.PayLog;
import com.ruoyi.door.domain.proxy.DoorOrderProxy;
import com.ruoyi.door.service.DoorOrderService;
import com.ruoyi.door.utils.baofu.BaoFuConstants;
import com.ruoyi.door.utils.baofu.BaofuUtil;
import com.ruoyi.door.utils.baofu.rsa.SignatureUtils;
import com.ruoyi.door.utils.baofu.util.FormatUtil;
import com.ruoyi.door.utils.baofu.util.SecurityUtil;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.ISysOperLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单信息Controller
 *
 * @author ruoyi
 * @date 2025-06-22
 */
@Api(value = "APP 订单信息管理", tags = "APP 订单信息管理")
@RestController
@Slf4j
@RequestMapping("/app-api/door/order-info")
public class AppDoorOrderController extends BaseController {
    @Autowired
    private EasyEntityQuery easyEntityQuery;
    @Autowired
    private DoorOrderService doorOrderService;
    @Autowired
    private ResourceLoader resourceLoader;
    @Autowired
    private ISysOperLogService iSysOperLogService;

    public String getResourcePath(String resourcePath) throws IOException {
        Resource resource = resourceLoader.getResource("classpath:" + resourcePath);
        File file = resource.getFile();
        return file.getAbsolutePath();
    }
    public InputStream getResourcePath2(String resourcePath) throws IOException {
        Resource resource = resourceLoader.getResource("classpath:" + resourcePath);
        return resource.getInputStream();
    }


    private EntityQueryable<DoorOrderProxy, DoorOrder> buildQuery(DoorOrder doorOrder) {
        EntityQueryable<DoorOrderProxy, DoorOrder> queryable = easyEntityQuery.queryable(DoorOrder.class)
                .where(x -> {
                    if (doorOrder.getId() != null) {
                        x.id().eq(doorOrder.getId());
                    }

                    if (doorOrder.getType() != null) {
                        x.type().eq(doorOrder.getType());
                    }

                    if (doorOrder.getTotalPrice() != null) {
                        x.totalPrice().eq(doorOrder.getTotalPrice());
                    }
                    if (doorOrder.getOrderStatus() != null) {
                        x.orderStatus().eq(doorOrder.getOrderStatus());
                    }
                    if (doorOrder.getPayTime() != null) {
                        x.payTime().eq(doorOrder.getPayTime());
                    }
                    if (StringUtils.isNotBlank(doorOrder.getTradeNo())) {
                        x.tradeNo().eq(doorOrder.getTradeNo());
                    }
                    if (StringUtils.isNotBlank(doorOrder.getOrderNo())) {
                        x.orderNo().eq(doorOrder.getOrderNo());
                    }
                    if (StringUtils.isNotBlank(doorOrder.getOpenid())) {
                        x.openid().like(doorOrder.getOpenid());
                    }
//                    x.memberId().eq(SecurityUtils.getAppUserId());
                    if (ObjectUtil.isNotNull(doorOrder.getUserId())) {
                        x.userId().eq(doorOrder.getUserId());
                    }
                })
                .orderBy(x -> x.createTime().desc());
        return queryable;
    }

    /**
     * 查询订单信息列表
     */
    @ApiOperation("查询订单信息列表")
    @GetMapping("/list")
    @Anonymous
    public TableDataInfo list(DoorOrder doorOrder) {
        startPage();
        EasyPageResult<DoorOrder> pageResult = buildQuery(doorOrder)
                .toPageResult(TableSupport.buildPageRequest().getPageNum(),
                        TableSupport.buildPageRequest().getPageSize());
        if (ObjectUtil.isNotNull(pageResult.getData())) {
            for (DoorOrder order : pageResult.getData()) {
                List<DoorOrderDetail> list = easyEntityQuery.queryable(DoorOrderDetail.class).where(x -> x.orderId().eq(order.getId())).toList();
                doorOrder.setDetails(list);
            }
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(pageResult.getData());
        rspData.setTotal(pageResult.getTotal());
        return rspData;
    }


    /**
     * 获取订单信息详细信息
     */
    @ApiOperation("获取订单信息详细信息")
    @GetMapping(value = "/{id}")
    @Anonymous
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        DoorOrder doorOrder = easyEntityQuery.queryable(DoorOrder.class).where(x -> x.id().eq(id))
                .firstOrNull();
        if (ObjectUtil.isNotNull(doorOrder)){
            List<DoorOrderDetail> list = easyEntityQuery.queryable(DoorOrderDetail.class).where(x -> x.orderId().eq(id)).toList();
            doorOrder.setDetails(list);
        }
        return success();
    }

    /**
     * 新增订单信息
     */
    @ApiOperation("新增订单信息")
    @Log(title = "订单信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Anonymous
    public AjaxResult add(@Validated @RequestBody AppOrderInfoCreateReqVO reqVO) {

        return AjaxResult.success(doorOrderService.add(reqVO));
    }

    @ApiOperation("提交订单信息")
    @PostMapping("/submit")
    @Anonymous
    public AjaxResult submit(@RequestBody AppOrderInfoSubmitReqVO reqVO) {

        //发起第三方支付;返回给前端支付信息
        return AjaxResult.success(doorOrderService.submit(reqVO));
    }

    @ApiOperation("银行支付回调")
    @Log(title = "套餐信息", businessType = BusinessType.INSERT)
    @RequestMapping(value = "/callback-bank", method = RequestMethod.POST)
    @Anonymous
    public String payCallbackBank(@RequestBody String jsonBody, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String> formMap = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();

        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            // 假设每个字段只有一个值
            formMap.put(entry.getKey(), entry.getValue()[0]);
        }
        PayLog payLog = new PayLog();
        payLog.setRequestBody(JSONObject.toJSONString(formMap));
        payLog.setCreateTime(DateUtils.getNowDate());
        easyEntityQuery.insertable(payLog).executeRows();
        // 记录日志
        SysOperLog sysOperLog = new SysOperLog();
        sysOperLog.setTitle("银行支付回调");
        sysOperLog.setJsonResult(JSONObject.toJSONString(formMap));
        sysOperLog.setStatus(1);
        iSysOperLogService.insertOperlog(sysOperLog);
        log.info("协议支付回调进来了: formMap={}", JSONObject.toJSONString(formMap));


        if (!formMap.containsKey("resp_code")) {
            throw new Exception("缺少resp_code参数！");
        }
        if (formMap.get("resp_code").toString().equals("S")) {
            log.info("支付成功！");

            String order_id = request.getParameter("order_id");
            String trans_id = request.getParameter("trans_id");//商户订单号
            doorOrderService.payCallBack(trans_id, order_id);
        }


        return "OK";
    }

    @ApiOperation("微信支付回调")
    @RequestMapping(value = "/callback-jh", method = RequestMethod.POST)
    @Anonymous
    public String payCallbackJh( HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String> formMap = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();

        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            // 假设每个字段只有一个值
            formMap.put(entry.getKey(), entry.getValue()[0]);
        }
        String uuid = IdUtil.fastUUID();

        PayLog payLog = new PayLog();
        payLog.setUuid(uuid);
        payLog.setType("聚合支付回调:formMap");
        payLog.setRequestBody(JSONObject.toJSONString(formMap));
        payLog.setCreateTime(DateUtils.getNowDate());
        easyEntityQuery.insertable(payLog).executeRows();
        // 记录日志
        log.info("聚合支付回调进来了: formMap={}", JSONObject.toJSONString(formMap));

        if (!formMap.containsKey("signStr")) {
            throw new Exception("缺少验签参数！");
        }
        String RSign = formMap.get("signStr");
        String dataContent = formMap.get("dataContent");

        log.info("返回的验签值：" + RSign);
        log.info("返回的dataContent：" + dataContent);
        payLog = new PayLog();
        payLog.setUuid(uuid);
        payLog.setType("聚合支付回调:dataContent");
        payLog.setRequestBody(dataContent);
        payLog.setCreateTime(DateUtils.getNowDate());
        easyEntityQuery.insertable(payLog).executeRows();
        JSONObject jsonObject = JSONObject.parseObject(dataContent);

        // 获取字段值
        String resultCode = jsonObject.getString("resultCode");
        String tradeNo = jsonObject.getString("tradeNo");
        String outTradeNo = jsonObject.getString("outTradeNo");
        log.info("返回的resultCode：" + resultCode);
        log.info("返回的tradeNo：" + tradeNo);
        log.info("返回的outTradeNo：" + outTradeNo);

        if (StrUtil.isEmpty(resultCode)) {
            throw new Exception("缺少resultCode参数！");
        }
        if (resultCode.equals("SUCCESS")) {
            log.info("支付成功！");
            doorOrderService.payCallBack(outTradeNo, tradeNo);
        }

        String cerpath = BaofuUtil.getPath(BaoFuConstants.CER_PATH);

//        if (SignatureUtils.verifySignature(cerpath, dataContent, RSign)) {
//            log.info("验签：Yes");//验签成功
//            if (!formMap.containsKey("returnCode")) {
//                throw new Exception("缺少returnCode参数！");
//            }
//            if (!formMap.get("returnCode").equals("SUCCESS")) {
//                throw new Exception("returnCode不是SUCCESS");
//            }
//
//            if (!formMap.containsKey("resultCode")) {
//                throw new Exception("缺少resultCode参数！");
//            }
//            if (formMap.get("resultCode").toString().equals("SUCCESS")) {
//                log.info("支付成功！");
//
//                String tradeNo = formMap.get("tradeNo");
//                String outTradeNo = formMap.get("outTradeNo");//商户订单号
//                doorOrderService.payCallBack(outTradeNo, tradeNo);
//            }
//        } else {
//            log.info("验签：NO");
//        }

        return "OK";
    }
}
